<template>
  <div class="container">
    <div class="header">
      <h1>小程序模块管理</h1>
      <div class="actions">
        <el-button @click="fetchModuleList">刷新数据</el-button>
      </div>
    </div>
    
    <div class="module-description">
      <el-alert
        type="info"
        :closable="false"
        show-icon>
        <h3>小程序首页模块配置</h3>
        <p>在此配置小程序首页显示的模块、顺序及可见性。使用上下按钮调整顺序，开关控制模块的显示/隐藏。</p>
      </el-alert>
    </div>
    
    <el-card class="module-card" v-loading="loading">
      <div v-for="(module, index) in moduleList" :key="module.id" class="module-item">
        <div class="module-icon">
          <el-image 
            v-if="module.icon" 
            :src="module.icon" 
            fit="cover" 
            style="width: 40px; height: 40px"
          />
          <el-icon v-else><Setting /></el-icon>
        </div>
        <div class="module-info">
          <div class="module-name">{{ module.moduleName }}</div>
          <div class="module-code">模块代码: {{ module.moduleCode }}</div>
          <div class="module-path" v-if="module.pagePath">页面路径: {{ module.pagePath }}</div>
        </div>
        <div class="module-actions">
          <div class="order-controls">
            <el-button 
              type="primary" 
              circle 
              :icon="ArrowUp"
              :disabled="index === 0"
              @click="moveUp(index)"
              size="small">
            </el-button>
            <div class="order-number">{{ module.sortOrder }}</div>
            <el-button 
              type="primary" 
              circle 
              :icon="ArrowDown"
              :disabled="index === moduleList.length - 1"
              @click="moveDown(index)"
              size="small">
            </el-button>
          </div>
          <el-tooltip :content="module.isVisible ? '当前可见' : '当前隐藏'" placement="top">
            <el-switch
              v-model="module.isVisible"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => toggleModuleVisibility(module, val)"
            />
          </el-tooltip>
        </div>
      </div>
      
      <div class="no-modules" v-if="!loading && (!moduleList || moduleList.length === 0)">
        <el-empty description="暂无模块数据"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowUp, ArrowDown, Setting } from '@element-plus/icons-vue'
import { getAllModules, updateModuleVisibility, updateModuleSort } from '@/api/module'

const loading = ref(false)
const moduleList = ref([])
const originalOrder = ref([])

// 获取模块列表
const fetchModuleList = async () => {
  loading.value = true
  try {
    const res = await getAllModules()
    if (Array.isArray(res)) {
      // 确保按排序字段排序
      moduleList.value = res.sort((a, b) => a.sortOrder - b.sortOrder)
      saveOriginalOrder()
      // 只在页面初次加载时弹一次成功提示
      if (!fetchModuleList.hasLoaded) {
        ElMessage.success('模块列表加载成功')
        fetchModuleList.hasLoaded = true
      }
    } else {
      ElMessage.error('获取模块列表失败')
    }
  } catch (error) {
    console.error('获取模块列表出错:', error)
    ElMessage.error('获取模块列表失败')
  } finally {
    loading.value = false
  }
}
fetchModuleList.hasLoaded = false

// 保存原始排序，用于对比
const saveOriginalOrder = () => {
  originalOrder.value = moduleList.value.map(item => ({
    id: item.id,
    moduleCode: item.moduleCode,
    sortOrder: item.sortOrder
  }))
}

// 切换模块显示状态
const toggleModuleVisibility = async (module, value) => {
  try {
    await updateModuleVisibility(module.moduleCode, value === 1)
    //ElMessage.success(`${module.moduleName} ${value === 1 ? '已设为显示' : '已设为隐藏'}`)
  } catch (error) {
    console.error('更新模块显示状态出错:', error)
    ElMessage.error('更新模块显示状态失败')
    // 恢复原值
    module.isVisible = module.isVisible === 1 ? 0 : 1
  }
}

// 上移模块
const moveUp = async (index) => {
  if (index <= 0) return
  const current = moduleList.value[index]
  const prev = moduleList.value[index - 1]
  const tempOrder = current.sortOrder
  current.sortOrder = prev.sortOrder
  prev.sortOrder = tempOrder
  moduleList.value.splice(index - 1, 2, current, prev)
  try {
    await updateModuleSort(current.moduleCode, current.sortOrder)
    await updateModuleSort(prev.moduleCode, prev.sortOrder)
    //ElMessage.success('模块顺序已更新')
  } catch (error) {
    console.error('更新模块顺序出错:', error)
    ElMessage.error('更新模块顺序失败')
    fetchModuleList() // 出错时重新加载
  }
}

// 下移模块
const moveDown = async (index) => {
  if (index >= moduleList.value.length - 1) return
  const current = moduleList.value[index]
  const next = moduleList.value[index + 1]
  const tempOrder = current.sortOrder
  current.sortOrder = next.sortOrder
  next.sortOrder = tempOrder
  moduleList.value.splice(index, 2, next, current)
  try {
    await updateModuleSort(current.moduleCode, current.sortOrder)
    await updateModuleSort(next.moduleCode, next.sortOrder)
    //ElMessage.success('模块顺序已更新')
  } catch (error) {
    console.error('更新模块顺序出错:', error)
    ElMessage.error('更新模块顺序失败')
    fetchModuleList() // 出错时重新加载
  }
}

onMounted(() => {
  fetchModuleList()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
    
    .actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .module-description {
    margin-bottom: 20px;
  }
  
  .module-card {
    margin-bottom: 20px;
    
    .module-item {
      display: flex;
      align-items: center;
      padding: 15px;
      border-bottom: 1px solid #ebeef5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .module-icon {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        border-radius: 4px;
        background: #f5f7fa;
      }
      
      .module-info {
        flex: 1;
        
        .module-name {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 5px;
        }
        
        .module-code, .module-path {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .module-actions {
        display: flex;
        align-items: center;
        gap: 20px;
        
        .order-controls {
          display: flex;
          align-items: center;
          flex-direction: column;
          gap: 5px;
          
          .order-number {
            font-size: 14px;
            font-weight: bold;
            color: #606266;
          }
        }
      }
    }
  }
  
  .no-modules {
    padding: 40px 0;
  }
}
</style> 